package org.jeecg.modules.iot.mqtt.server.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.base.BaseMap;
import org.jeecg.common.modules.redis.client.JeecgRedisClient;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.iot.jtt808.JTT808Decoder;
import org.jeecg.modules.iot.jtt808.req.LocationNewMsg;
import org.jeecg.modules.iot.jtt808.vo.JT808DataPacket;
import org.jeecg.modules.iot.cache.EBikeCache;
import org.jeecg.modules.iot.mqtt.entity.MqttMessageJson;
import org.jeecg.modules.iot.model.FieldStatus;
import org.jeecg.modules.iot.model.Jt808Control.JT808AttributeConverter;
import org.jeecg.modules.iot.model.KalmanFilter;
import org.jeecg.modules.iot.model.Location;
import org.jeecg.modules.iot.model.Track.Tracking;
import org.jeecg.modules.iot.model.power.TaiPower;
import org.jeecg.modules.iot.mqtt.server.service.MqttRecvCommand;
import org.jeecg.modules.iot.mqtt.server.service.MqttSendCommand;
import org.jeecg.modules.iot.service.*;
import org.jeecg.modules.iot.utils.JT808Utils;
import org.jeecg.modules.iot.utils.JsonUtil;

import org.jeecg.modules.websocket.constant.WsMessageConstant;
import org.jeecg.modules.websocket.enums.WsBussinesType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.yzh.protocol.t808.T0200;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@RequiredArgsConstructor
@Component("0200")
public class Command_0200 implements MqttRecvCommand  , MqttSendCommand {
    
    private final ILocationService locationService;

    @Autowired
    private RedisUtil redisUtil;


    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    private final EBikeCache eBikeCache;

    private final IPowerService powerService;

    private final IConsumptionService consumptionService;

    private JeecgRedisClient jeecgRedisClient;

    private static final int KILOMETER_WINDOW = 10;

    private KalmanFilter kalmanFilter= new KalmanFilter(0.1, 1, 0);;

    private static final double WGS84_A = 6378137.0; // 地球椭球体长半轴，单位为米
    private static final double WGS84_B = 6356752.314245; // 地球椭球体短半轴，单位为米
    private static final double WGS84_F = 1 / 298.257223563; // 地球椭球体的扁率

    private static final String LOCATION_PREFIX = "location:"; // Redis key 前缀

    //private static final ConcurrentHashMap<String, CompletableFuture<Location>> futuresMap = new ConcurrentHashMap<>();
    private static final String NATIONAL_STANDARD_SPEED_LIMIT_KEY = "vehicle:%s:nationalStandardSpeedLimit"; //  Redis key 格式
    @Override
    public void execute(MqttMessageJson mqttMessageJson) throws Exception {
        JT808DataPacket jt808DataPacket=JTT808Decoder.decode(mqttMessageJson.getData());

        T0200 msg = (T0200) JT808Utils.decode(mqttMessageJson.getData());

       // 创建 Location 对象并设置属性
        Location location = createLocation(mqttMessageJson, msg);
        // 主动推送位置信息到前端（异步）
        pushLocationToFrontEndAsync(mqttMessageJson, location);

    }


    @Override
    public void execute(MqttMessageJson mqttMessageJson, MqttMessageJson mqttMessageJsonReturn) throws Exception {

        //kafkaTemplate.send("location-topic",mqttMessageJson.getData());
        T0200 msg = (T0200) JT808Utils.decode(mqttMessageJson.getData());
        Map<Integer, Object> attributeConverter=   msg.getAttributes();
        Map<String, Object>  stringObjectMap= JT808AttributeConverter.convertAttributes(attributeConverter);
        LocationNewMsg locationNewMsg = (LocationNewMsg) JTT808Decoder.decode(mqttMessageJson.getData());

       /* if (snnNumber<3) {
            return;
        }*/
        long startTime = System.nanoTime();
        JT808DataPacket jt808DataPacket=JTT808Decoder.decode(mqttMessageJson.getData());
        /*updatePhoneIfIdMismatch(msg.getClientId(),mqttMessageJson.getId());*/
        // 创建 Location 对象并设置属性
        Location location = createLocation(mqttMessageJson, msg);


        // 主动推送位置信息到前端（异步）
        pushLocationToFrontEndAsync(mqttMessageJson, location);
        // 添加位置信息到数据库（同步）
        //addLocationToDatabase(location);
        //添加到redis
        //updateLocationInRedis(mqttMessageJson.getId(),location);
        long endTime = System.nanoTime();
        System.out.println("处理时间-----------Storage time: " + (endTime - startTime) / 1e6 + " ms");

    }
    private Location createLocation(MqttMessageJson mqttMessageJson, T0200 msg) {

        Map<Integer, Object> attributeConverter=   msg.getAttributes();
        Map<String, Object>  stringObjectMap= JT808AttributeConverter.convertAttributes(attributeConverter);
        Integer snnNumber= (Integer) stringObjectMap.get("gnssSatelliteCount");
        Location location = new Location();
        location.setTs(new Timestamp(new Date().getTime()));
        location.setDeviceId(mqttMessageJson.getId());
        location.setAlarm(msg.getWarnBit());
        location.setStatusField(msg.getStatusBit());
        location.setLatitude(msg.getLatitude() * 1.0 / 1000000);
        location.setLongitude(msg.getLongitude() * 1.0 / 1000000);
        location.setSnnNumber(snnNumber);
        location.setSpeed((short) msg.getSpeed());
        location.setDirection((short) msg.getDirection());
        location.setElevation((short) msg.getAltitude());
        location.setSeq(mqttMessageJson.getSeq());
        return location;
    }

    public void updatePhoneIfIdMismatch(String t0200ClientId, String carCode) {
        String formattedId = carCode.substring(3); // 去掉 carCode 前三位数字

        // 不足12位，在前面补零
        String paddedClientId = String.format("%012d", Long.parseLong(t0200ClientId));

        if (!formattedId.equals(paddedClientId)) {
            //TODO 更新车辆中控SN
            // 查询 carCode 对应的所有车辆
            /*List<RentalCar> cars = rentalCarMapper.selectList(
                    new QueryWrapper<RentalCar>().eq("car_code", carCode)
            );

            // 更新车辆的 phone
            for (RentalCar car : cars) {
                car.setPhone(paddedClientId);
                rentalCarMapper.updateById(car);
            }*/
        }
    }

    private void pushLocationToFrontEndAsync(MqttMessageJson mqttMessageJson, Location location) {
        CompletableFuture.runAsync(() -> {
            //ObjectMapper objectMapper = new ObjectMapper();
            //String sseMessage = objectMapper.writeValueAsString(location);
            //String loc=JsonUtil.createPubLocation(location);
            //String sseMessage=JsonUtil.createPubJson(WsBussinesType.LOCATION.getCode(),true,location);
            eBikeCache.updateVehicleLocation(mqttMessageJson.getId(),location.getLongitude(),location.getLatitude());
            FieldStatus fieldStatus=new FieldStatus(location.getStatusField());
            eBikeCache.setFieldStatus(location.getDeviceId(), fieldStatus);
            Location lastLocation=locationService.queryByDeviceId(mqttMessageJson.getId());
            //计算两个时间如果差值在一分钟以外就取之前的总里程
            if (lastLocation!=null){
                updateMileage(location, lastLocation);
            }
            //计算功耗
            //calculatePowerConsumption(location);

            calculatePowerConsumptionNew(location);
            // @TODO 未存到数据库
            //eBikeCache.setVehicleLocationWithDetails(location);
            // 添加位置信息到数据库（同步）
            addLocationToDatabase(location);
            Tracking tracking=new Tracking();
            String onlineStatus = eBikeCache.getVehicleOnlineStatus(mqttMessageJson.getId());
            location.setOnlineStatus(onlineStatus);

            //tracking.setRMileage(roundToTwoDecimalPlaces( (location.getRMileage()/1000)));
            tracking.setRMileage(roundToTwoDecimalPlaces((float) Math.abs(location.getRMileage()/1000.0)));
            String trackingJson=JsonUtil.createPubJson(WsBussinesType.TRACKING.getCode(),true,tracking);
            String locationJson=JsonUtil.createPubJson(WsBussinesType.LOCATION.getCode(),true,location);
            /*根据车辆编号推送数据*/
            BaseMap trackingParams = new BaseMap();
            trackingParams.add("terminalCode", mqttMessageJson.getId());
            trackingParams.add("message", trackingJson);
            jeecgRedisClient.sendMessage(WsMessageConstant.EBIKE_REALTIME_MESSAGE, trackingParams);

            BaseMap locationParams = new BaseMap();
            locationParams.add("terminalCode", mqttMessageJson.getId());
            locationParams.add("message", locationJson);
            jeecgRedisClient.sendMessage(WsMessageConstant.EBIKE_REALTIME_MESSAGE, locationParams);

            ObjectMapper objectMapper = new ObjectMapper();
            // 获取运动模式状态
            String sportModeRedisKey = String.format(NATIONAL_STANDARD_SPEED_LIMIT_KEY, mqttMessageJson.getId());
            Boolean sportModeEnabled = (Boolean) redisUtil.get(sportModeRedisKey); // 从 Redis 获取运动模式状态
            boolean sportMode = sportModeEnabled != null && sportModeEnabled; // 简化逻辑
            fieldStatus.setSportMode(sportMode);
            String satusJson=JsonUtil.createPubJson(WsBussinesType.OTHER.getCode(),true,fieldStatus);
            BaseMap satusParams = new BaseMap();
            satusParams.add("terminalCode", mqttMessageJson.getId());
            satusParams.add("message", satusJson);
            jeecgRedisClient.sendMessage(WsMessageConstant.EBIKE_REALTIME_MESSAGE, satusParams);
        });
    }

    public void calculatePowerConsumptionNew(Location currentLocation) {
        String deviceId = currentLocation.getDeviceId();
        Location lastLocation = locationService.queryByDeviceId(deviceId);
        TaiPower fPower = powerService.queryLastByDeviceId(deviceId);
        if (lastLocation != null  ) {

            if (fPower == null) {
                return; // 处理 fPower 为 null 的情况
            }

            double distance = calculateDistance(lastLocation.getLatitude(), lastLocation.getLongitude(),
                    currentLocation.getLatitude(), currentLocation.getLongitude());

            // 里程以米为单位进行计算
            float newMileage = (lastLocation.getMileage() == null ? 0f : lastLocation.getMileage()) + (float) distance;
            float newSMileage = (lastLocation.getSMileage() == null ? 0f : lastLocation.getSMileage()) + (float) distance;
            float newFMileage = (lastLocation.getFMileage() == null ? 0f : lastLocation.getFMileage()) + (float) distance;

            currentLocation.setMileage(newMileage);
            currentLocation.setSMileage(newSMileage);
            currentLocation.setFMileage(newFMileage);
            System.out.println(currentLocation.getFMileage() + "距离");
           /* if (currentLocation.getFMileage() > 1000) {

                Consumption lastConsumption = consumptionService.queryLatestByDeviceId(deviceId);
                if (lastConsumption != null) {
                    TaiPower prev500Power = powerService.queryNearestAfterTime( deviceId, lastConsumption.getTs());
                    if (prev500Power == null) {

                        Consumption consumption = new Consumption();
                        consumption.setDeviceId(deviceId);
                        consumption.setTs(currentLocation.getTs());
                        consumptionService.add(consumption);
                        currentLocation.setFMileage(0f); // 重置 500 米里程
                        return; // 处理 prev500Power 为 null 的情况
                    }
                    float energy500Diff = prev500Power.getEPower()-fPower.getEPower() ;
                    System.out.println(energy500Diff+"消耗的能量");
                    Consumption consumption = new Consumption();
                    consumption.setTs(currentLocation.getTs());
                    consumption.setDeviceId(deviceId);
                    consumption.setFMileage(currentLocation.getFMileage()); // 使用 500 米作为里程
                    consumption.setEpower(energy500Diff);
                    float energy500Consumption = energy500Diff / currentLocation.getFMileage(); // 计算 500 米的能耗
                    if (energy500Consumption==0){
                        consumption.setEConsum(lastConsumption.getEConsum());
                    }else {
                        consumption.setEConsum(energy500Consumption);
                    }

                    consumptionService.add(consumption);
                }else {
                    Consumption consumption = new Consumption();
                    consumption.setDeviceId(deviceId);
                    consumption.setTs(currentLocation.getTs());
                    consumptionService.add(consumption);
                }
                currentLocation.setFMileage(0f); // 重置 500 米里程
            }
        }*/

        /*    float rmilege = 0f;
            float avrConsum = consumptionService.calculateMileageWeightedAverageEConsum(deviceId, 10);*/

            float rmilege = 0f;
            float avrConsum = consumptionService.calculateAverageEConsum(deviceId, 10);

            if (avrConsum != 0) {
                //rmilege = fPower.getRPow() / avrConsum;
                rmilege=fPower.getRPow()/avrConsum;
                 System.out.println("方差平均"+rmilege+"加权平均"+rmilege);
            }
            if (rmilege==0){
                //TODO 计算剩余里程  获取车辆类型的初始功耗
                /*LambdaQueryWrapper<RentalCar> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(RentalCar::getCarCode, deviceId);
                List<RentalCar> existingCars = rentalCarMapper.selectList(queryWrapper);
                if (existingCars.size() > 0) {
                    Long carTypeId=  existingCars.get(0).getCarTypeId();
                    if (carTypeId!=null){
                        RentalCarType carType=rentalCarTypeMapper.selectById(carTypeId);
                        if (carType!=null && carType.getInitialConsumption()!=null){
                            rmilege = fPower.getRPow() / carType.getInitialConsumption();
                        }
                    }
                }*/
            }
            currentLocation.setRMileage(rmilege);
        }
    }

    public void calculatePowerConsumption(Location currentLocation) {
        Float energyConsumption = 0f;
        String deviceId = currentLocation.getDeviceId();
        Location lastLocation = locationService.queryByDeviceId(deviceId);
        // 检查是否存在上一次位置信息
        if (lastLocation!=null){
            // 每过 500 米计算一次能耗（每过500清零一次）
            if ( currentLocation.getSpeed()>0 && currentLocation.getFMileage()>500) {
                TaiPower fPower = powerService.queryLastByDeviceId(deviceId);

                if (currentLocation == null || fPower == null) {
                    throw new IllegalArgumentException("无法获取当前时刻的位置信息或电量信息");
                }

                // 获取最近KILOMETER_WINDOW公里的 Location 和 TaiPower 数据
                Float totalEnergyConsumption = 0f;//在最近 KILOMETER_WINDOW 公里内车辆消耗的总电量。
                Float totalMileage = 0f;//在最近 KILOMETER_WINDOW 公里内车行驶的总公里数。
                // 计算 500 米能耗
                Float total500Mileage = 0f;
                Float energy500Consumption = 0f;
                 Location prev500Location = locationService.queryOneKmBefore(deviceId, currentLocation.getMileage() - 500);
                 if (prev500Location!=null){
                     TaiPower prev500Power = powerService.queryNearestAfterTime(deviceId, prev500Location.getTs());
                     float energy500Diff =  fPower.getEPower()-prev500Power.getEPower();
                     total500Mileage  = (currentLocation.getMileage()-prev500Location.getMileage());
                     //计算这500米的平均功耗作为瞬时功耗 如果不在3W到40W之间就不记录统计。

                     if (total500Mileage != 0) {
                         energy500Consumption = energy500Diff / total500Mileage;
                     } else {
                         energy500Consumption = lastLocation.getSConsum();
                     }
                     // 判断平均功耗是否在合理范围内
                     Float averagePower = calculateAveragePower(prev500Power, fPower);
                     if (averagePower > 1000 || averagePower < 3) {
                         // 不在合理范围内，使用上一次的 SConsum
                         energy500Consumption = lastLocation.getSConsum();
                     }
                     long timeDiffMillis = fPower.getTs().getTime() - prev500Power.getTs().getTime();
                     float timeDiffSeconds = timeDiffMillis / 1000f;

                     // 判断时间差是否在合理范围内
                     if (timeDiffSeconds < 40 || timeDiffSeconds > 250) {
                         energy500Consumption = lastLocation.getSConsum();
                     }
                     currentLocation.setSConsum(energy500Consumption);

                 }
                //前一时刻的位置信息
                // 计算 1 公里能耗
                Location locP=currentLocation;
                TaiPower powP = fPower;
                for (int i = 1; i <= KILOMETER_WINDOW; i++) {
                    Location prevLocation = locationService.queryOneKmBefore(deviceId, locP.getMileage() - i*500);
                    if (prevLocation == null) {
                        break;
                    }

                    TaiPower prevPower = powerService.queryNearestAfterTime(deviceId, prevLocation.getTs());
                    if (prevPower == null) {
                        break;
                    }

                    Float averagePower = calculateAveragePower(prevPower, powP);
                    if (averagePower > 50 || averagePower < 3) {
                        //不在合理范围内就跳出
                        break;
                    }
                    long timeDiffMillis = prevPower.getTs().getTime() - powP.getTs().getTime();
                    float timeDiffSeconds = timeDiffMillis / 1000f;

                    // 判断时间差是否在合理范围内
                    if (timeDiffSeconds < 40 || timeDiffSeconds > 250) {
                        break;
                    }
                    float energyDiff = powP.getEPower()- prevPower.getEPower() ;

                    // 忽略充电过程中出现的负值
                    if (energyDiff < 0) {
                        continue;
                    }

                    totalEnergyConsumption +=   energyDiff  ;
                    totalMileage += (locP.getMileage()-prevLocation.getMileage());
                    locP=prevLocation;
                    powP=prevPower;
                }

                if (totalMileage != 0) {
                    energyConsumption = totalEnergyConsumption / totalMileage;
                } else {
                    energyConsumption = lastLocation.getEConsum();
                }
                float weightedEnergyConsumption=0;
                if (energyConsumption!=0 && currentLocation.getSConsum()!=0){
                    weightedEnergyConsumption= (energyConsumption * 0.4f) + (currentLocation.getSConsum() * 0.6f);
                }

                currentLocation.setEConsum(energyConsumption);
                if (weightedEnergyConsumption != 0) {
                    currentLocation.setRMileage(fPower.getRPow() / weightedEnergyConsumption);
                    currentLocation.setEConsum(weightedEnergyConsumption);
                } else if (weightedEnergyConsumption==0 && energyConsumption != 0) {
                    currentLocation.setRMileage(fPower.getRPow() / energyConsumption);
                    currentLocation.setEConsum(energyConsumption);
                } else {
                    currentLocation.setEConsum(lastLocation.getEConsum());
                    if (currentLocation.getEConsum() != 0) {
                        //currentLocation.setRMileage(fPower.getRPow() / lastLocation.getEConsum());
                        currentLocation.setRMileage(fPower.getRPow() / currentLocation.getSConsum());
                    } else {
                        currentLocation.setRMileage(0f);
                    }

                }
                currentLocation.setFMileage(0f);
            } else {
                // 如果速度为零，使用上一次的能耗和剩余里程

                TaiPower fPower = powerService.queryLastByDeviceId(deviceId);
                currentLocation.setSConsum(lastLocation.getSConsum());
                if (lastLocation.getEConsum() != null && lastLocation.getEConsum() != 0) {
                    currentLocation.setEConsum(lastLocation.getEConsum());
                    if (lastLocation.getEConsum()!=0){
                        currentLocation.setRMileage(fPower.getRPow() / lastLocation.getEConsum());
                    }else {
                        currentLocation.setRMileage(0f);
                    }

                } else {
                    currentLocation.setEConsum(0f);
                    currentLocation.setRMileage(0f);
                }

            }
        }

    }
    /*计算两个之间的平均功耗 单位（瓦w） */
    public float calculateAveragePower(TaiPower startPower, TaiPower endPower) {
        // 检查参数是否有效
        if (startPower == null || endPower == null || startPower.getTs() == null || endPower.getTs() == null) {
            throw new IllegalArgumentException("电量信息或时间戳无效");
        }

        // 计算时间差，单位为小时
        long timeDiffMillis = endPower.getTs().getTime() - startPower.getTs().getTime();
        float timeDiffHours = timeDiffMillis / (1000f * 60 * 60);

        // 计算能量差，单位为瓦时
        float energyDiffWh = startPower.getRPow() - endPower.getRPow();

        // 计算平均功率，单位为瓦特
        float averagePower = energyDiffWh / timeDiffHours;

        return averagePower;
    }

    private double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double L = Math.toRadians(lon2 - lon1);
        double U1 = Math.atan((1 - WGS84_F) * Math.tan(Math.toRadians(lat1)));
        double U2 = Math.atan((1 - WGS84_F) * Math.tan(Math.toRadians(lat2)));
        double sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
        double sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);

        double lambda = L, lambdaP;
        int iterLimit = 100;
        double cosSqAlpha, sinSigma, cos2SigmaM, cosSigma, sigma;

        do {
            double sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);
            sinSigma = Math.sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda)
                    + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda));
            if (sinSigma == 0) return 0;

            cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda;
            sigma = Math.atan2(sinSigma, cosSigma);
            double sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma;
            cosSqAlpha = 1 - sinAlpha * sinAlpha;
            cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha;
            if (Double.isNaN(cos2SigmaM)) cos2SigmaM = 0;

            double C = WGS84_F / 16 * cosSqAlpha * (4 + WGS84_F * (4 - 3 * cosSqAlpha));
            lambdaP = lambda;
            lambda = L + (1 - C) * WGS84_F * sinAlpha
                    * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
        } while (Math.abs(lambda - lambdaP) > 1e-12 && --iterLimit > 0);

        if (iterLimit == 0) return Double.NaN;

        double uSq = cosSqAlpha * (WGS84_A * WGS84_A - WGS84_B * WGS84_B) / (WGS84_B * WGS84_B);
        double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
        double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
        double deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)
                - B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));

        return WGS84_B * A * (sigma - deltaSigma);
    }
    private float roundToTwoDecimalPlaces(float value) {
        return BigDecimal.valueOf(value).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
    }
    private void addLocationToDatabase(Location location) {
        //J

        locationService.add(location);
    }
   /* private void updateLocationInRedis(String carCode, Location location) {
        String redisKey = LOCATION_PREFIX + carCode;
        redisTemplate.opsForValue().set(redisKey, location); // 直接覆盖更新
    }*/


    private void updateMileage(Location location, Location lastLocation) {
        if (lastLocation == null) {
            return;
        }

        long timeDiff = location.getTs().getTime() - lastLocation.getTs().getTime();
        Float lastMileage = lastLocation.getMileage();
        Float lastDMileage=lastLocation.getDMileage();
        Float lastSMileage=lastLocation.getSMileage();
        Float lastFMileage=lastLocation.getFMileage();

        FieldStatus fieldStatus=new FieldStatus(location.getStatusField());



        if (timeDiff > 60 * 1000 ||  !fieldStatus.isAcc()) {
            location.setMileage(lastMileage);
            if (!fieldStatus.isAcc()){
                location.setSMileage(0f);
                System.out.println("单次里程设为0");
            }else {
                location.setSMileage(lastLocation.getSMileage());
                location.setFMileage(lastLocation.getFMileage());
            }
            return;
        }


        double distance = calculateDistance(lastLocation.getLatitude(), lastLocation.getLongitude(),
                location.getLatitude(), location.getLongitude());
        if (distance >= 1000) { // 如果 distance 不超过 1000 米
            distance=0;
        }
        //单次里程

        float newMileage = (lastMileage == null ? 0f : lastMileage) + (float) distance;
        float newSMileage = (lastSMileage == null ? 0f : lastSMileage) + (float) distance;
        float newFMileage = (lastFMileage == null ? 0f : lastFMileage) + (float) distance;
        location.setMileage(newMileage);
        location.setFMileage(newFMileage);
        location.setSMileage(newSMileage);
    }


}
